<?php
namespace app\admin\controller\v3;
use app\admin\Adminbase;
//use base\service\Gateway;
use app\common\model\Msg as MsgModel;
use app\common\model\MsgUser;
use app\common\model\MsgOrder;
use app\common\model\MsgSystem;
use app\common\model\MsgSystemRead;


// 相关文档 https://github.com/walkor/GatewayClient
// 相关文档 http://doc2.workerman.net/send-to-all.html
//Gateway::sendToAll($data);								向所有客户端发送消息
//Gateway::sendToClient($client_id, $data);			向某个客户端发送消息
//Gateway::closeClient($client_id); 						传递的消息不ok就踢掉对应客户端
//Gateway::isOnline($client_id);							在线返回1，不在线返回0
//Gateway::bindUid($client_id, $uid); 							
//Gateway::isUidOnline($uid);	
//Gateway::getClientIdByUid($uid); 	
//Gateway::unbindUid($client_id, $uid); 	
//Gateway::sendToUid($uid, $dat); 	
//Gateway::joinGroup($client_id, $group); 	
//Gateway::sendToGroup($group, $data); 	
//Gateway::leaveGroup($client_id, $group); 	
//Gateway::getClientCountByGroup($group);
//Gateway::getClientSessionsByGroup($group);
//Gateway::getAllClientCount();
//Gateway::getAllClientSessions();
//Gateway::setSession($client_id, $session);
//Gateway::updateSession($client_id, $session);
//Gateway::getSession($client_id);

//Gateway::$registerAddress = '127.0.0.1:1238';

//定义公共控制器并继承核心框架的控制器
class Csd extends Adminbase
{
	
	/**
	* 获取列表
	* /admin/v3/Csd/getList
	* 需要登录 
	* @is_need_login true
	*/
    public function getList()
    {
    	$request =  request();
    	$userinfo = $request->userInfo;
		
    	$mine = [
			"username"=> $userinfo['user_name'],
			"id"=> $userinfo['user_guid'],
			"status"=>$userinfo['land_status'] == 1 ? "online" : "hide",
			"sign"=> $userinfo['csd_sign'],
			"avatar"=> APP_PATH."/".str_replace("\\","/",
				db("systemUpload")->alias('c')
				->where('c.file_buss_type','用户信息')
				->where('c.file_type','头像')
				->where('c.file_guid',$userinfo['user_guid'])
				->field("c.file_path as file_path")
				->limit(0,1)
				->union("select 'Public/images/user_img.jpg' as file_path")
				->value('file_path')
			) 
		];
		$friend = [[
			"id"=>1, 
			"groupname"=> "客服列表", 
			"list"=> db('systemUser')->alias("a")
				->where("a.is_csd =1 or a.is_admin =1")
				->where("a.user_id",'<>',$userinfo['user_id'])
				->order('a.user_id asc')
				->field("if(1,'online','hide') as status")
				->field("a.user_guid as id")
				->field("a.user_name as username")
				->field( 
					db("systemUpload")->alias('c')
					->where('c.file_buss_type','用户信息')
					->where('c.file_type','头像')
					->where('c.file_guid = a.user_guid')
					->field("concat('".APP_PATH."/"."',c.file_path ) as file_path")
					->limit(0,1)
					->union("SELECT '".APP_PATH."/Public/images/user_img.jpg' as file_path")
					->buildSql()
				." avatar")
				->field("a.csd_sign as sign")
				->select()
		]];
		$group = [[ "groupname"=>"前端群","id"=> "101","avatar"=> ""]];
    	$data = [ "mine"=> $mine, "friend"=>$friend, "group"=> $group ];
    	return $this->ReSucess($data);
    }
	
	/**
	* 更新签名
	* /admin/v3/Csd/updateSign
	* 需要登录 
	* @is_need_login true
	*/
    public function updateSign($sign)
    {
    	try {
    		$data['csd_sign'] = $sign;
			model('systemUser')->where("user_id",request()->userInfo['user_id'])->update($data);
			return $this->ReSucess(true);
		} catch (Exception $e) {
			throw new \think\Exception( $e );
		}
    }
	
	
	/**
	* 发送
	* /admin/v3/Csd/sendMsg
	* 需要登录 
	* @is_need_login true
	*/
    public function sendMsg(){
    	
		$request =  request();
		$uid = $request->userInfo['user_guid'];
		$param = $request->post();
		
		//TODO 获取post参数
    	list($reciveId,$content,$contentType,$relationId) = [
    		$param['to']['id'] ?: 0,
    		$param['mine']['content'] ?: '',
    		$param['content_type'] ?: 1,
    		$param['relation_id'] ?: '',
    	];
		
		if(!$reciveId){
			return $this->ReError( "参数错误" );	
		}
		
		try {
			$db = new MsgModel;
	        $result = $db->send($uid,$reciveId,$content,$contentType,$relationId,1,1);
			if($result === false){
				return $this->ReError( $db->errorInfo );	
			}
			return $this->ReSucess($result);	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
    }
    
    
    /**
	* 获取聊天记录
	* /admin/v3/Csd/getCache
	* 需要登录 
	* @is_need_login true
	*/
    public function getCache($recive_id = 0,$is_log=false)
    {
		$user_guid  = request()->userInfo['user_guid'];	  
		$uniques = [$user_guid,$recive_id]; sort($uniques); $uniques = md5(join(",",$uniques));
    	try {
	    	$result  =  model('msgUser')
	    		->alias("a")
				->where("uniques", $uniques)
				->rightJoin(
					[ 	
						db("systemUser") ->field("user_guid,user_name,csd_sign")->field( 
							db("systemUpload")->alias('c') 
							->where('c.file_buss_type','用户信息')
							->where('c.file_type','头像')
							->where('c.file_guid = user_guid')
							->field("concat('".APP_PATH."/"."',c.file_path ) as file_path")
							->limit(0,1)
							->union("SELECT '".APP_PATH."/Public/images/user_img.jpg' as file_path")
							->buildSql() ." headimgurl"
						)
						->union(function($query){
  							$query
	  							->field('id as user_guid')
	      						->field('nickname as user_name')
	      						->field("'' as csd_sign")
	      						->field('avatarUrl as  headimgurl')
	      						->name('user');
        				})
        				->buildSql() => 'b'
					],
					'a.send_id = b.user_guid'
				)
				->order('a.add_time desc')
				->page(1,!$is_log ? 50 : 10000)
				->field("a.*,unix_timestamp(a.add_time) as timestamp,b.csd_sign")
				->field("b.user_name as send_name,b.headimgurl as send_avatar")
				->select()->toArray();
				
			return $this->ReSucess( array_reverse($result)	 );
			
		} catch (Exception $e) {
			throw new \think\Exception( $e );
		}
    }

	 /**
	* 获取聊天记录
	* /admin/v3/Csd/getNewsCache
	* 需要登录 
	* @is_need_login true
	*/
    public function getNewsCache()
    {
		$user_guid  = request()->userInfo['user_guid'];	  
    	try {
			$result  =  model('msgUser')->alias("a")
				->where("a.status",0)
				->where("a.recive_id", "=" ,$user_guid)
				->rightJoin(
					[ 	
						db("systemUser") ->field("user_guid,user_name,csd_sign")->field( 
							db("systemUpload")->alias('c') 
							->where('c.file_buss_type','用户信息')
							->where('c.file_type','头像')
							->where('c.file_guid = user_guid')
							->field("concat('".APP_PATH."/"."',c.file_path ) as file_path")
							->limit(0,1)
							->union("SELECT '".APP_PATH."/Public/images/user_img.jpg' as file_path")
							->buildSql() ." headimgurl"
						)
						->union(function($query){
  							$query
	  							->field('id as user_guid')
	      						->field('nickname as user_name')
	      						->field("'' as csd_sign")
	      						->field('avatarUrl as  headimgurl')
	      						->name('user');
        				})
        				->buildSql() => 'b'
					],
					'a.send_id = b.user_guid'
				)
				->group('a.send_id')
				->order('a.add_time desc')
				->page(1,50)
				->field("a.*,unix_timestamp(a.add_time) as timestamp,b.csd_sign")
				->field("b.user_name as send_name,b.headimgurl as send_avatar")
				->select();
				
			return $this->ReSucess( $result );
    	} catch (Exception $e) {
			throw new \think\Exception( $e );
		}
    }
    
	/**
	*  更新信息状态
	* /admin/v3/Csd/updateInfoStatus
	* 需要登录 
	* @is_need_login true
	*/
    public function updateInfoStatus($send_id,$recive_id,$status)
    {
    	try {
    		$res =  model('msg')
	    		->where("send_id",$send_id)
	    		->where("recive_id",$recive_id)
	    		->update(["unread_num"=>0]);
	    	$res =  model('msgUser')
	    		->where("send_id",$send_id)
	    		->where("recive_id",$recive_id)
	    		->update(["status"=>$status]);
//	    	Gateway::sendToUid($send_id, json_encode(["type"=>"getChatList"]) );	
			return $this->ReSucess( $result );
		} catch (Exception $e) {
			throw new \think\Exception( $e );
		}
    }
    
	
	/**
	*  获取订单聊天记录
	* /admin/v3/Csd/getOrderChat
	* 需要登录 
	* @is_need_login true
	*/
    public function getOrderChat($send_id,$order_no)
    {
    	try {
	    	$result  =  model('Chat')
	    		->where("order_no",$order_no)
	    		->select();
			return $this->ReSucess( $result );
		} catch (Exception $e) {
			throw new \think\Exception( $e );
		}
    }
	
	/**
	*  回复订单消息
	* /admin/v3/Csd/replyOrderChat
	* 需要登录 
	* @is_need_login true
	*/
    public function replyOrderChat()
    {
    	try {
    		$posData = request()->post();
	    	$data = [
	    		"send_id" => $posData['mine']['id'],
	    		"sign" => $posData['mine']['sign'],
	    		"username"=>$posData['mine']['username'],
	    		"avatar"=>$posData['mine']['avatar'],
	    		"content" => $posData['mine']['content'],
	    		"type" => $posData['to']['type'],
	    		"status" => 1,
	    		"mine"=>false,
	    		"recive_id" => $posData['to']['id'],
	    		"order_no"=> $posData["order_no"]
	    	];
	    	// 保存
	    	$msg = model('Chat');
	    	$msg->allowField(["send_id", "content","type", "status", "send_id", "recive_id", "order_no"])->save($data);
			$msg->where('order_no',$data['order_no'])
				->where('send_id',$data['recive_id'])
				->update(["recive_id"=>$data['send_id'],"status"=>2]);
	    	//发送
	    	$data['id'] = $msg->id;
	    	$sendMsg=[ "data"=>$data, "type"=>"msg" ];
	    	//Gateway::sendToUid( $data["recive_id"] , json_encode($sendMsg) );
	    	//Gateway::sendToUid( $data["recive_id"] , json_encode(["type"=>"getChatList"]) );
	    	//返回
			return $this->ReSucess( $data );
		} catch (Exception $e) {
			throw new \think\Exception( $e );
		}
    }
	
	
}


